package logic

import (
	"context"
	"encoding/hex"

	"charging_pile/devices/internal/svc"
	"charging_pile/devices/pb"
	iot "charging_pile/util"
	"charging_pile/util/protocol/jiuxing"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetBillingModelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSetBillingModelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetBillingModelLogic {
	return &SetBillingModelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SetBillingModelLogic) SetBillingModel(in *pb.SetBillingModelReq) (*pb.SetBillingModelResp, error) {
	// todo: add your logic here and delete this line

	return &pb.SetBillingModelResp{}, nil
}

func ConvertSetBillingModelRpc2JxPkg(in *pb.SetBillingModelReq) *jiuxing.Package {

	pl := jiuxing.Msg37{
		Tm: iot.FormatJxTime(),
		BM: jiuxing.BillMode{
			Ver:          uint16(in.BillingModelVersion),
			ParkRate:     uint32(in.ParkingModel),
			TimeSegNum:   byte(in.SegNum),
			TimeSegRates: []jiuxing.TimeSegRate{},
		},
	}
	for _, v := range in.SegmentModel {
		pl.BM.TimeSegRates = append(pl.BM.TimeSegRates, jiuxing.TimeSegRate{
			ElectricRate:  uint32(v.PwrModel),
			ServiceCharge: uint32(v.ServeModel),
			BeginHour:     byte(v.StartHour),
			BeginMinute:   byte(v.StartMinute),
			Tp:            byte(v.SegmentType),
		})
	}

	p := pl.Encode()
	sn, _ := hex.DecodeString(in.Pile)
	pkg := &jiuxing.Package{
		Cmd:        0x1F,
		Sn:         sn,
		Encryption: 1,
		PackageLen: uint16(len(p)),
		Payload:    p,
		Check:      0,
	}

	return pkg
}
